package cn.wubo.one.table.ai.service.impl;

import cn.wubo.dynamic.loader.utility.compiler.DynamicCompiler;
import cn.wubo.entity.sql.web.EntityWebService;
import cn.wubo.one.table.ai.OneTableAiProperties;
import cn.wubo.one.table.ai.service.IOneTableAiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class OneTableAiServiceImpl implements IOneTableAiService {

    private final ChatClient chatClient;
    private final EntityWebService entityWebService;
    private final OneTableAiProperties properties;

    public OneTableAiServiceImpl(ChatClient chatClient, EntityWebService entityWebService, OneTableAiProperties properties) {
        this.chatClient = chatClient;
        this.entityWebService = entityWebService;
        this.properties = properties;
    }

    @Override
    public Flux<String> buildRequirement(String text) {
        return chatClient.prompt()
                .system(properties.getRequirementBuilder())
                .user(text)
                .stream()
                .content();
    }

    @Override
    public Flux<String> buildClass(String text) {
        return chatClient.prompt()
                .system(properties.getClassBuilder())
                .user(text)
                .stream()
                .content();
    }

    @Override
    public Map<String, Object> buildWeb(String text) {
        Map<String, Object> result = new HashMap<>();
        String id = UUID.randomUUID().toString();

        if (text.indexOf("<think>") > 0)
            text = text.substring(text.indexOf("</think>") + 8);
        if (text.contains("```java"))
            text = text.substring(text.indexOf("```java") + 7, text.lastIndexOf("```"));

        result.put("javaSourceCode", text);

        Class<?> clazz;
        try {
            clazz = DynamicCompiler.compileAndLoad(text);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        entityWebService.build(id, clazz);

        result.put("id", id);
        return result;
    }
}
